<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 登录</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="config.js"></script>
    <style>
        .login-actions {
            margin-top: 15px;
        }
        .login-actions .btn {
            margin-top: 10px;
        }
        .system-info {
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        .system-info small {
            color: #666;
            font-size: 12px;
            opacity: 0.8;
        }
        .login-header h1 {
            margin: 10px 0 5px 0;
        }
        .login-header p {
            margin: 0 0 5px 0;
        }
    </style>
</head>
<body>
    <!-- 登录页面 -->
    <div id="loginPage" class="page active">
        <div class="login-container">
            <div class="login-card">
                <div class="login-header">
                    <i class="fas fa-book"></i>
                    <h1 id="systemName">图书馆管理系统</h1>
                    <p id="libraryName">Library Management System</p>
                    <div class="system-info">
                        <small id="systemVersion">v1.0.0</small>
                        <small id="copyrightInfo">© 2024 成都工业学院</small>
                    </div>
                </div>
                <form id="loginForm" class="login-form">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <input type="password" id="password" name="password" required>
                    </div>
                    <button type="submit" class="btn btn-primary btn-full">登录</button>
                    <div class="login-actions">
                        <button type="button" class="btn btn-secondary btn-full" onclick="clearLoginStatus()">清除登录状态</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 用户管理API
        const UserAPI = {
            // 用户登录
            login: (loginData) => api.post('/api/users/login', loginData)
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            }
        };

        // 全局变量
        let currentUser = null;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            
            // 延迟更新系统信息，确保全局配置已加载
            setTimeout(() => {
                updateSystemInfo();
            }, 500);
        });

        // 初始化应用
        function initializeApp() {
            // 检查本地登录状态或尝试 URL 自动登录
            checkLoginStatus();
            if (!currentUser) {
                tryAutoLoginFromUrl();
            }
            
            // 绑定事件监听器
            bindEventListeners();
            
            // 更新登录页面系统信息
            updateSystemInfo();
        }

        // 如果地址栏带有 username/password，则静默登录并写入 localStorage
        async function tryAutoLoginFromUrl() {
            try {
                const url = new URL(window.location.href);
                const u = url.searchParams.get('username');
                const p = url.searchParams.get('password');
                if (!u || !p) return;
                Utils.showLoading();
                const res = await UserAPI.login({ username: u, password: p });
                if (res && res.result === 'SUCCESS') {
                    const loginData = res.data;
                    
                    // 保存用户信息和权限信息
                    localStorage.setItem('currentUser', JSON.stringify(loginData.userInfo));
                    localStorage.setItem('authToken', loginData.token);
                    localStorage.setItem('userMenus', JSON.stringify(loginData.menuList));
                    localStorage.setItem('userPermissions', JSON.stringify(loginData.permissions));
                    
                    currentUser = loginData.userInfo;
                    
                    // 清理地址栏中的敏感参数
                    url.searchParams.delete('password');
                    url.searchParams.delete('username');
                    window.history.replaceState({}, document.title, url.toString());
                    // 跳转到仪表板页面
                    window.location.href = 'dashboard.html';
                }
            } catch (e) {
                // 忽略失败，保持登录页
            } finally {
                Utils.hideLoading();
            }
        }

        // 绑定事件监听器
        function bindEventListeners() {
            // 登录表单提交
            const loginForm = document.getElementById('loginForm');
            if (loginForm) {
                loginForm.addEventListener('submit', handleLogin);
            }
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            const authToken = localStorage.getItem('authToken');
            
            // 只有同时存在用户信息和token才认为是已登录状态
            if (savedUser && authToken) {
                try {
                    currentUser = JSON.parse(savedUser);
                    // 验证token是否有效（简单检查）
                    if (authToken && authToken.length > 10) {
                        console.log('检测到有效登录状态，跳转到仪表板');
                        // 如果已登录，跳转到仪表板
                        window.location.href = 'dashboard.html';
                    }
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                    // 清除无效的登录信息
                    clearLoginStatus();
                }
            }
        }

        // 清除登录状态
        function clearLoginStatus() {
            console.log('清除登录状态');
            localStorage.removeItem('currentUser');
            localStorage.removeItem('authToken');
            localStorage.removeItem('userMenus');
            localStorage.removeItem('userPermissions');
            currentUser = null;
            // 不自动刷新页面，避免循环
        }

        // 更新登录页面系统信息
        async function updateSystemInfo() {
            try {
                // 等待全局配置加载完成
                if (window.globalConfig) {
                    await window.globalConfig.init();
                    const config = window.globalConfig.getAllConfig();
                    
                    // 更新系统名称
                    const systemNameEl = document.getElementById('systemName');
                    if (systemNameEl && config.system_name) {
                        systemNameEl.textContent = config.system_name;
                    }
                    
                    // 更新图书馆名称
                    const libraryNameEl = document.getElementById('libraryName');
                    if (libraryNameEl && config.library_name) {
                        libraryNameEl.textContent = config.library_name;
                    }
                    
                    // 更新系统版本
                    const systemVersionEl = document.getElementById('systemVersion');
                    if (systemVersionEl && config.system_version) {
                        systemVersionEl.textContent = 'v' + config.system_version;
                    }
                    
                    // 更新版权信息
                    const copyrightInfoEl = document.getElementById('copyrightInfo');
                    if (copyrightInfoEl && config.copyright_info) {
                        copyrightInfoEl.textContent = config.copyright_info;
                    }
                    
                    console.log('登录页面系统信息已更新:', config);
                }
            } catch (error) {
                console.warn('更新登录页面系统信息失败:', error);
            }
        }

        // 处理登录
        async function handleLogin(event) {
            event.preventDefault();
            
            const formData = new FormData(event.target);
            const loginData = {
                username: formData.get('username'),
                password: formData.get('password')
            };

            // 基本验证
            if (!loginData.username || !loginData.password) {
                Utils.showMessage('请输入用户名和密码', 'warning');
                return;
            }

            // 验证密码长度
            if (window.globalConfig) {
                const passwordValidation = window.globalConfig.validatePasswordLength(loginData.password);
                if (!passwordValidation.valid) {
                    Utils.showMessage(passwordValidation.message, 'warning');
                    return;
                }
            }
            
            try {
                Utils.showLoading();
                const response = await UserAPI.login(loginData);
                
                if (response.result === 'SUCCESS') {
                    const loginData = response.data;
                    
                    // 保存用户信息和权限信息
                    localStorage.setItem('currentUser', JSON.stringify(loginData.userInfo));
                    localStorage.setItem('authToken', loginData.token);
                    localStorage.setItem('userMenus', JSON.stringify(loginData.menuList));
                    localStorage.setItem('userPermissions', JSON.stringify(loginData.permissions));
                    
                    currentUser = loginData.userInfo;
                    
                    Utils.showMessage('登录成功', 'success');
                    // 跳转到仪表板页面
                    setTimeout(() => {
                        window.location.href = 'dashboard.html';
                    }, 1000);
                } else {
                    Utils.showMessage(response.message || '登录失败', 'error');
                }
            } catch (error) {
                Utils.showMessage(error.message || '登录失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }
    </script>
</body>
</html>
